package org.hry.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;

public class SafeHandler extends ByteToMessageDecoder{
    /**
     * 假设上线是10个字节
     */
    private static final int MAX_FRAME_SIZE = 10;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readable = in.readableBytes();
        if (readable > MAX_FRAME_SIZE) {
            in.skipBytes(readable);
            throw new TooLongFrameException("已经超过10个字节了");
        }
        ByteBuf buf = in.retainedDuplicate();
        out.add(buf);
        in.skipBytes(in.readableBytes());
    }
}
